<template>
  <div class="app-container">
    <el-form :model="queryParam" ref="queryForm" :inline="true" @submit.native.prevent="submitForm">
      <el-form-item label="申请人:">
        <el-input v-model="queryParam.userName" placeholder="请输入申请人姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="职位名称:">
        <el-input v-model="queryParam.title" placeholder="请输入职位名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="公司名称:">
        <el-input v-model="queryParam.companyName" :disabled="role !== 3" placeholder="请输入公司名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态:">
        <el-select v-model="queryParam.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="submitForm">查询</el-button>
        <el-button icon="el-icon-refresh" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="listLoading" :data="tableData" border fit highlight-current-row style="width: 100%">
      <el-table-column label="申请人" :formatter="row => row.user?.userName || '未知'"/>
      <el-table-column label="职位名称" :formatter="row => row.jobPostings?.title || '未知'"/>
      <el-table-column label="公司名称" :formatter="row => row.jobPostings?.companyName || '未知'"/>
      <el-table-column label="申请时间" :formatter="row => formatDate(row.appliedAt)"/>
      <el-table-column prop="status" label="状态">
        <template slot-scope="{row}">
          <el-tag :type="getStatusType(row.status)">
            {{ formatStatus(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="MBTI类型" :formatter="row => formatMBTITypes(row.jobMBTIS)"/>
      <el-table-column width="200px" label="操作" align="center">
        <template slot-scope="{row}">
          <div class="action-buttons">
            <el-button size="mini" type="primary" @click="viewDetails(row)">申请人信息</el-button>
            <el-button
              size="mini"
              type="success"
              @click="updateStatus(row)"
              v-if="row.status === 0">
              更新状态
            </el-button>
            <el-button
              size="mini"
              type="info"
              @click="showJobDetails(row)">
              职位信息
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParam.pageNum"
      :limit.sync="queryParam.pageSize"
      @pagination="search"/>

    <!-- Status Update Dialog -->
    <el-dialog title="更新申请状态" :visible.sync="statusDialogVisible" width="400px">
      <el-form :model="statusForm" label-width="80px">
        <el-form-item label="状态">
          <el-select v-model="statusForm.status">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="statusDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveStatus" :loading="saveLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- Job Details Dialog -->
    <el-dialog title="职位详细信息" :visible.sync="jobDetailsDialogVisible" width="700px">
      <div v-if="currentJobDetails">
        <!-- 基本信息 - 使用两列布局 -->
        <el-descriptions :column="2" border>
          <el-descriptions-item label="职位名称">{{ currentJobDetails.title }}</el-descriptions-item>
          <el-descriptions-item label="公司名称">{{ currentJobDetails.companyName }}</el-descriptions-item>
          <el-descriptions-item label="薪资范围">{{ currentJobDetails.wages }}</el-descriptions-item>
          <el-descriptions-item label="招聘人数">{{ currentJobDetails.count }}</el-descriptions-item>
          <el-descriptions-item label="发布时间">{{ formatDate(currentJobDetails.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentJobDetails.status === 1 ? 'success' : 'info'">
              {{ currentJobDetails.status === 1 ? '招聘中' : '已结束' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 使用标签页分隔详细内容 -->
        <el-tabs class="job-detail-tabs">
          <el-tab-pane label="职位描述">
            <div class="detail-content">{{ currentJobDetails.description }}</div>
          </el-tab-pane>
          <el-tab-pane label="职位要求">
            <div class="detail-content">{{ currentJobDetails.requirements }}</div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="jobDetailsDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 申请人信息弹窗 -->
    <el-dialog title="申请人详细信息" :visible.sync="userDetailsDialogVisible" width="500px">
      <div v-if="currentUserDetails" class="user-details-container">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用户名">{{ currentUserDetails.userName }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ currentUserDetails.realName || '未提供' }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ formatSex(currentUserDetails.sex) }}</el-descriptions-item>
          <el-descriptions-item label="电话">{{ currentUserDetails.phone || '未提供' }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ currentUserDetails.email || '未提供' }}</el-descriptions-item>
          <el-descriptions-item label="MBTI类型">{{ currentUserDetails.mbti || '未提供' }}</el-descriptions-item>
        </el-descriptions>

        <div class="resume-actions" v-if="currentUserDetails.biographicalNotes">
          <el-button type="primary" icon="el-icon-document" @click="viewResume">查看简历</el-button>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDetailsDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { mapActions, mapState } from 'vuex'
import api from '@/api/application'

export default {
  components: { Pagination },
  data () {
    return {
      queryParam: {
        status: null,
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        userName: null,
        title: null
      },
      statusOptions: [
        { value: 0, label: '待处理' },
        { value: 1, label: '已通过' },
        { value: 2, label: '已拒绝' },
        { value: 3, label: '已撤回' }
      ],
      user: null,
      role: '',
      listLoading: true,
      tableData: [],
      total: 0,
      statusDialogVisible: false,
      saveLoading: false,
      statusForm: {
        applicationId: null,
        status: null
      },
      jobDetailsDialogVisible: false,
      currentJobDetails: null,
      userDetailsDialogVisible: false,
      currentUserDetails: null
    }
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  methods: {
    ...mapActions('user', ['initUserInfo']),
    formatStatus (status) {
      const statusMap = {
        0: '待处理',
        1: '已通过',
        2: '已拒绝',
        3: '已撤回'
      }
      return statusMap[status] || '未知'
    },
    getStatusType (status) {
      const typeMap = {
        0: 'info',
        1: 'success',
        2: 'danger',
        3: 'warning'
      }
      return typeMap[status] || ''
    },
    formatDate (date) {
      if (!date) return '未知';

      // 处理数组格式的日期 [year, month, day, hour, minute, second]
      if (Array.isArray(date)) {
        // JavaScript 中月份是从 0 开始的，所以需要将月份减 1
        const [year, month, day, hour, minute, second] = date;
        return new Date(year, month - 1, day, hour, minute, second).toLocaleString();
      }

      // 处理常规日期格式
      return new Date(date).toLocaleString();
    },
    search () {
      this.listLoading = true

      // 创建一个新的参数对象
      const params = {
        pageIndex: this.queryParam.pageNum,
        pageSize: this.queryParam.pageSize
      }

      // 只添加有值的参数
      if (this.queryParam.status !== null && this.queryParam.status !== undefined) {
        params.status = Number(this.queryParam.status) // 确保是数字类型
      }

      if (this.queryParam.companyId) {
        params.companyId = Number(this.queryParam.companyId) // 确保是数字类型
      }

      if (this.queryParam.userName) {
        params.userName = this.queryParam.userName.trim()
      }

      if (this.queryParam.title) {
        params.title = this.queryParam.title.trim()
      }

      if (this.queryParam.companyName) {
        params.companyName = this.queryParam.companyName.trim()
      }

      console.log('发送搜索参数:', params)

      api.list(params)
        .then(response => {
          if (response.data && response.data.response) {
            this.tableData = response.data.response.list || []
            this.total = response.data.response.total || 0
          } else {
            console.error('Unexpected response format:', response)
            this.$message.error('获取数据格式异常')
            this.tableData = []
            this.total = 0
          }
        })
        .catch(error => {
          console.error('Error fetching application list:', error)
          this.$message.error('获取申请列表失败')
          this.tableData = []
          this.total = 0
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    submitForm () {
      this.queryParam.pageNum = 1
      // 更新日志输出，使用正确的参数名称
      console.log('搜索参数:', {
        userName: this.queryParam.userName,
        title: this.queryParam.title,
        companyName: this.queryParam.companyName,
        status: this.queryParam.status
      })
      this.search()
    },
    resetForm () {
      // 保存当前的公司名称（如果用户角色是2）
      const preserveCompanyName = this.role === 2 ? this.queryParam.companyName : null

      // 重置查询参数
      this.queryParam = {
        status: null,
        pageNum: 1,
        pageSize: 10,
        companyId: this.userInfo ? this.userInfo.companyId : null,
        userName: null,
        title: null,
        companyName: null
      }

      // 如果用户角色是2，恢复公司名称
      if (this.role === 2) {
        this.queryParam.companyName = preserveCompanyName
      }

      this.search()
    },
    viewDetails (row) {
      this.currentUserDetails = row.user
      this.userDetailsDialogVisible = true
    },
    updateStatus (row) {
      this.statusForm.applicationId = row.applicationId
      this.statusForm.status = row.status
      this.statusDialogVisible = true
    },
    saveStatus () {
      this.saveLoading = true
      api.updateStatus(this.statusForm.applicationId, this.statusForm.status)
        .then(response => {
          this.$message.success('状态更新成功')
          this.statusDialogVisible = false
          // 刷新列表
          this.search()
        })
        .catch(error => {
          console.error('Error updating application status:', error)
          this.$message.error('状态更新失败')
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    formatMBTITypes (jobMBTIS) {
      if (Array.isArray(jobMBTIS) && jobMBTIS.length > 0) {
        return jobMBTIS.map(item => item.mbtiType).join(', ')
      }
      return '未知'
    },
    showJobDetails (row) {
      this.currentJobDetails = row.jobPostings
      this.jobDetailsDialogVisible = true
    },
    formatSex (sex) {
      if (sex === 1) return '男'
      if (sex === 0) return '女'
      return '未知'
    },
    viewResume() {
      if (this.currentUserDetails && this.currentUserDetails.biographicalNotes) {
        // 直接从 public/resume 目录访问文件
        const resumeUrl = `/resume/${this.currentUserDetails.biographicalNotes}`;

        // 在新标签页中打开简历
        window.open(resumeUrl, '_blank');
      } else {
        this.$message.warning('没有找到简历文件');
      }
    }
  },
  created () {
    this.initUserInfo().then(() => {
      if (this.userInfo) {
        this.queryParam.companyId = this.userInfo.companyId
        this.user = this.userInfo
        this.role = this.userInfo.role

        // 如果用户角色是2，自动填充公司名称
        if (this.role === 2 && this.userInfo.companyName) {
          this.queryParam.companyName = this.userInfo.companyName
        }
      }
      this.search()
    })
  }
}
</script>

<style scoped>
.link-left {
  margin-right: 8px;
}
.el-button + .el-button {
  margin-left: 8px;
}
.job-detail-tabs {
  margin-top: 15px;
}
.detail-content {
  white-space: pre-line;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  line-height: 1.6;
  max-height: 200px;
  overflow-y: auto;
}
.user-details-container {
  padding: 10px;
}
.resume-actions {
  margin-top: 15px;
  text-align: center;
}
.action-buttons {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex-wrap: nowrap;
  gap: 8px;
}

.action-buttons el-button {
  width: 100%;
  height: 40px;
}
</style>
